import java.io.*;
import javax.microedition.lcdui.Graphics;
//#if TILESTYPE_SEPARATE
	import javax.microedition.lcdui.Image;
//#endif


class TileIndex {
    short nPicID;
    byte bOptions;
    byte bHeight[] = new byte[6];
}

public class TileDrawer {
	public static final byte bOpt_Collisable = 1;
	public static final byte bOpt_HaveMask = 2;

	public static int nTileWidth;
	public static int nTileHVDiv;
	public static TileIndex mTiles[];

	//#if TILESTYPE_SEPARATE
		public static Image mImages[];
	//#endif

	/**
	 *
	 */
	public static void LoadTiles() {
		DataInputStream dis;
		try {
			dis = new DataInputStream(MTMMidlet.the_class.getResourceAsStream( "/res/tiles.dat" ));
			if (dis != null) {
				int n_tiles_count = dis.readInt();
				nTileWidth = dis.readInt();

				nTileHVDiv = nTileWidth / 6;

				mTiles = new TileIndex[n_tiles_count];
				//#if TILESTYPE_SEPARATE
					mImages = new Image[n_tiles_count];
				//#endif

				int tt;
				for ( int j=0; j<n_tiles_count; j++ ) {
					TileIndex tnd = mTiles[j] = new TileIndex();
					tnd.nPicID = dis.readShort();
					tnd.bOptions = dis.readByte();
					tnd.bHeight[0] = dis.readByte();
					tnd.bHeight[1] = dis.readByte();
					tnd.bHeight[2] = dis.readByte();
					tnd.bHeight[3] = dis.readByte();
					tnd.bHeight[4] = dis.readByte();
					tnd.bHeight[5] = dis.readByte();
					tt = GameWorld.tileType(tnd.nPicID);
					if ((tt == PicID.nPicID_p0_hz_lev1_top_off) || (tt == PicID.nPicID_p0_hz_lev2_top_off)) {
						tnd.bHeight[0]++;
						tnd.bHeight[1]++;
						tnd.bHeight[2]++;
						tnd.bHeight[3]++;
						tnd.bHeight[4]++;
						tnd.bHeight[5]++;
					}
					//#if TILESTYPE_SEPARATE
						mImages[j] = Image.createImage(nTileWidth, nTileWidth);
						PicDrawer.DrawPic( mImages[j].getGraphics(), 0, 0, mTiles[j].nPicID, Graphics.TOP | Graphics.LEFT );
					//#endif
				}
				dis.close();
			}
		}
		catch (Exception e) {
		}
		finally {
			//#if TILESTYPE_SEPARATE
				PicDrawer.mImages[0] = null;
			//#endif
			dis = null;
			System.gc();
		}
	}

	/**
	 *
	 */
	public static void DrawTile(Graphics g, int x, int y, int n_tile_id) {
		if ((n_tile_id >= 0) && (n_tile_id < mTiles.length)) {
			//#if TILESTYPE_SEPARATE
				g.drawImage(mImages[n_tile_id], x, y, Graphics.TOP | Graphics.LEFT);
			//#else
				PicDrawer.DrawPic( g, x, y, mTiles[n_tile_id].nPicID, Graphics.TOP | Graphics.LEFT );
			//#endif
		}
	}
}
